package com.xywl.escort.view.order.purchase.all;


import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.PurchaseOrderAdapter;
import com.xywl.escort.base.BaseFragment;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.LogisticsResp;
import com.xywl.escort.bean.PurchaseOrderDetailBean;
import com.xywl.escort.bean.PurchaseOrderListResp;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.widget.CustomDialog;
import com.xywl.escort.widget.CustomDialog2;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import dagger.android.support.AndroidSupportInjection;
import timber.log.Timber;

/**
 * 采购订单-全部
 */

public class PurchaseOrderFragment extends BaseFragment implements PurchaseOrderContract.View, SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    @BindView(R.id.recycler_order)
    RecyclerView mRecyclerOrder;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;

    @Inject
    PurchaseOrderContract.Presenter mPresenter;
    private PurchaseOrderAdapter mAdapter;
    private int mPosition;

    private int pageNum = 1;
    private boolean isEnd;

    private CustomDialog mDialog;
    private CustomDialog2 mDialog2;

    private List<PurchaseOrderDetailBean> mList = new ArrayList<>();

    public PurchaseOrderFragment() {
        // Required empty public constructor
    }

    public static PurchaseOrderFragment newInstance(int param1) {
        PurchaseOrderFragment fragment = new PurchaseOrderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getArguments()) {
            mPosition = getArguments().getInt(ARG_PARAM1, -1);
        }
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_purchase_order;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        LinearLayoutManager manager = new LinearLayoutManager(this.getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerOrder.setLayoutManager(manager);

        mAdapter = new PurchaseOrderAdapter(R.layout.item_order_purchase, mList);
        mRecyclerOrder.setAdapter(mAdapter);

        View emptyView = LayoutInflater.from(this.getActivity()).inflate(R.layout.layout_empty_view, null);
        TextView tvEmpty = emptyView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无数据");
        mAdapter.setEmptyView(emptyView);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PurchaseOrderDetailBean listBean = mList.get(position);
                Timber.e("orderId= " + listBean.id);
                ARouter.getInstance().build("/xy/order/purchase/detail")
                        .withString("orderId", listBean.id)
                        .navigation();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mSwipeRefreshLayout.setEnabled(false);
                mRecyclerOrder.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setEnabled(false);
                        if (isEnd) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                            mSwipeRefreshLayout.setEnabled(true);
                        } else {
                            //成功获取更多数据
                            mPresenter.loadOrder(mPosition, pageNum);
                        }
                    }
                }, 200);
            }
        }, mRecyclerOrder);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PurchaseOrderDetailBean listBean = mList.get(position);
                switch (view.getId()) {
                    case R.id.btn_order_delete: {
                        delete(listBean.id, position);
                    }
                    break;
                    case R.id.btn_cancel_order: {
                        cancel(listBean.id, position);
                    }
                    break;
                    case R.id.btn_order_payment: {
                        payment(listBean.id, listBean.orderAmountTotal);
                    }
                    break;
                    case R.id.btn_order_remind: {
                        remind(listBean.id);
                    }
                    break;
                    case R.id.btn_order_confirm_receipt: {
                        confirm(listBean.id);
                    }
                    break;
                    case R.id.btn_order_logistics: {
                        logistics(listBean.id);
                    }
                    break;
                    case R.id.btn_buy_again: {
                        buyAgain(listBean.id);
                    }
                    break;
                    case R.id.btn_order_comment: {
                        comment(listBean);
                    }
                    break;
                    default:
                        break;
                }
            }
        });
    }

    private void logistics(final String id) {
        mPresenter.orderLogistics(id);
    }

    private void comment(PurchaseOrderDetailBean listBean) {
        ARouter.getInstance()
                .build("/xy/order/evaluate")
                .withString("orderId", listBean.id)
                .navigation();
    }

    private void payment(String orderId, BigDecimal payMoney) {
        ARouter.getInstance()
                .build("/xy/product/pay/dialog")
                .withString("orderId", orderId)
                .withObject("payMoney", payMoney)
                .withInt("type", 1)
                .navigation();
    }

    private void buyAgain(String orderId) {
        ARouter.getInstance()
                .build("/xy/buy/again")
                .withString("orderId", orderId)
                .navigation();
    }

    private void delete(final String id, final int position) {
        mDialog = new CustomDialog.Builder(PurchaseOrderFragment.this.getActivity())
                .setMessage("是否删除该订单？")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mDialog.dismiss();

                        mPresenter.orderDelete(id, position);
                    }
                }).setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create();
        mDialog.show();
    }

    private void cancel(final String id, final int position) {
        mDialog = new CustomDialog.Builder(PurchaseOrderFragment.this.getActivity())
                .setMessage("是否取消订单？")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mDialog.dismiss();

                        mPresenter.orderCancel(id, position);
                    }
                }).setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create();
        mDialog.show();
    }

    private void remind(String id) {
        mPresenter.remind(id);
    }

    private void confirm(final String id) {
        mDialog = new CustomDialog.Builder(PurchaseOrderFragment.this.getActivity())
                .setMessage("请确认是否已经收到货物？")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mDialog.dismiss();

                        mPresenter.confirm(id);
                    }
                }).setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create();
        mDialog.show();
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        pageNum = 1;
        mPresenter.takeView(this);
        mPresenter.loadOrder(mPosition, pageNum);
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        mAdapter.setEnableLoadMore(false);
        mPresenter.loadOrder(mPosition, pageNum);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void loadOrderSuccess(PurchaseOrderListResp resp) {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerOrder.setVisibility(View.VISIBLE);

        if (null != resp.data && null != resp.data.list) {
            List<PurchaseOrderDetailBean> list = resp.data.list;
            if (pageNum == 1) {
                mList.clear();
            }
            mList.addAll(list);
            if (pageNum >= resp.data.pages) {
                isEnd = true;
            } else {
                isEnd = false;
                pageNum += 1;
            }
            mAdapter.setNewData(mList);
            mAdapter.loadMoreComplete();
            mSwipeRefreshLayout.setEnabled(true);
        }
    }

    @Override
    public void loadOrderFailure() {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerOrder.setVisibility(View.VISIBLE);
    }

    @Override
    public void orderCancelSuccess(BaseResp resp, int position) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), "取消订单成功");
        }
        mList.remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void orderCancelFailure(String msg) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
    }

    @Override
    public void orderDeleteSuccess(BaseResp resp, int position) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), "删除订单成功");
        }
        mList.remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void orderDeleteFailure(String msg) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
    }

    @Override
    public void orderRemindSuccess(BaseResp resp) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), "提醒发货成功！！！");
        }
    }

    @Override
    public void orderRemindFailure(String msg) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
    }

    @Override
    public void orderConfirmSuccess(BaseResp resp) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), "操作成功！！！");
        }
    }

    @Override
    public void orderConfirmFailure(String msg) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
    }

    @Override
    public void orderLogisticsSuccess(LogisticsResp.DataBean dataBean) {
        String title = dataBean.expressCompany + "  单号: " + dataBean.expressNo;
        String deliveryTime = "发货时间: " + dataBean.deliveryTime;
        mDialog2 = new CustomDialog2
                .Builder(this.getActivity())
                .setTitle(title)
                .setMessage(deliveryTime)
                .create();
        mDialog2.show();
    }

    @Override
    public void orderLogisticsFailure(String msg) {
        Timber.tag("PurchaseOrderFragment").e("orderLogisticsFailure");
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mDialog2) {
            mDialog2.dismiss();
            mDialog2 = null;
        }
    }
}
